package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.vo.ApLoginVo;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;
    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {

        LambdaQueryWrapper<ApUser> wrapper = Wrappers.<ApUser>lambdaQuery();
        wrapper.eq(ApUser::getPhone,dto.getPhone());
        //1.从数据库中根据电话获取用户信息
        ApUser apUser = apUserMapper.selectOne(wrapper);
        //2.判断密码是否正确
        //boolean checkpw = BCrypt.checkpw(dto.getPassword(), apUser.getPassword());//校验两个密码是否相等
        if (!BCrypt.checkpw(dto.getPassword(), apUser.getPassword())){
            //4.不正确返回登录失败
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //3.密码正确生成token并返回ApLoginVo
        String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
        ApLoginVo apLoginVo = ApLoginVo.builder().id(apUser.getId())
                .name(apUser.getName())
                .phone(apUser.getPhone())
                .token(token).build();
        return ResponseResult.okResult(apLoginVo);
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
